import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
import matplotlib

# 设置字体
matplotlib.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei', 'FangSong']
matplotlib.rcParams['font.size'] = 15
matplotlib.rcParams['axes.unicode_minus'] = False

# 读取数据
Accidents = pd.read_csv('spider/clean_data.csv')

# 数据清洗,去除缺失值
Accidents = Accidents.dropna(subset=['car_structure', 'car_score', 'car_price'])

# 对标签进行编码
leixing_str = {}
leixing_list = list(Accidents['car_price'].value_counts().index)
for i in range(len(leixing_list)):
    leixing_str[leixing_list[i]] = i
Accidents['car_price'] = Accidents['car_price'].map(leixing_str)

# 检查数据类型
print(Accidents.info())  # 输出数据结构信息

# 选择数值特征进行聚类
X = Accidents[['car_structure', 'car_score', 'car_price']]

# 检查 X 的数据类型
print(X.dtypes)

# 标准化数据
try:
    minimum = X.min()
    maximum = X.max()
    X = (X - minimum) / (maximum - minimum)
except Exception as e:
    print("标准化数据时出现错误:", e)
    raise

# 使用 KMeans 进行聚类
km = KMeans(n_clusters=5, random_state=0).fit(X)
label_pred = km.labels_
Accidents['cluster'] = label_pred

# 输出聚类中心
print(km.inertia_, km.cluster_centers_)

# 保存每个集群的均值到 CSV 文件
X['cluster'] = label_pred
X.groupby("cluster").mean().to_csv('julei5.csv')

# 绘制聚类结果
X.plot.scatter(x='car_score', y='car_price', c='cluster', colormap='viridis')
plt.savefig('static/image/聚类结果展示 - car_score和car_price.png')
plt.show()

X.plot.scatter(x='car_structure', y='car_price', c='cluster', colormap='viridis')
plt.savefig('static/image/聚类结果展示 - car_structure和car_price.png')
plt.show()